import { Component, Renderer2, ElementRef } from "@angular/core";
import {
  Router,
  ActivatedRoute,
  ActivatedRouteSnapshot,
  RouterState,
  RouterStateSnapshot
} from "@angular/router";
import { SignInService } from "./blog/user/sign-in/sign-in.service";
import { SignUpService } from "./blog/user/sign-up/sign-up.service";
import { merge } from "rxjs";

@Component({
  selector: "app-root",
  templateUrl: "./app.component.html",
  styleUrls: ["./app.component.scss"]
})
export class AppComponent {
  public currentUser: any;
  private globalClickCallbackFn: Function;

  constructor(
    public elementRef: ElementRef,
    public renderer: Renderer2,
    public router: Router,
    public activatedRoute: ActivatedRoute,
    public signInService: SignInService,
    public signUpService: SignUpService
  ) {}

  ngOnInit() {
    this.globalClickCallbackFn = this.renderer.listen(
      this.elementRef.nativeElement,
      "click",
      (event: any) => {
        console.log("全局监听点击事件>" + event);
      }
    );

    this.currentUser = JSON.parse(localStorage.getItem("currentUser"));
    console.log("currentUser-----", this.currentUser);

    merge(
      this.signInService.currentUser,
      this.signUpService.currentUser
    ).subscribe(
      res => {
        this.currentUser = res;

        let activatedRouteSnapshot: ActivatedRouteSnapshot = this.activatedRoute
          .snapshot;
        let routerState: RouterState = this.router.routerState;
        let routerStateSnapshot: RouterStateSnapshot = routerState.snapshot;
        if (routerStateSnapshot.url.includes("/login")) {
          this.router.navigateByUrl("/home");
        }
      },
      err => {
        console.log(err);
      },
      () => {
        console.log("appComponent complete");
      }
    );
  }

  ngOnDestroy() {
    if (this.globalClickCallbackFn) {
      this.globalClickCallbackFn();
    }
  }

  public doLogout(): void {
    this.signInService.logout();
    this.router.navigateByUrl("");
  }
}
